<script setup lang="ts">
defineOptions({
  name: "factory"
});

import { ref, reactive, inject, nextTick, getCurrentInstance } from "vue";
import { PxMessage } from "px-ui";
import pmTitle from "./pmTitle.vue";
import pmTable from "./pmTable.vue";
import { queryFactoryPMGanttList, queryFactoryPMList } from "@/api/modules/fab";
import { ChartTypeType, ChartTypeKey, SelectionChangeCallBackType, SelectionChangeCallBackTypeKey } from "../utils";
import dayjs from "dayjs";

const { proxy }: any = getCurrentInstance();

const lock = defineModel("lock", { type: Boolean, default: false });

// gunter  甘特图   chart  table图
const chartType = inject<ChartTypeType>(ChartTypeKey, ref<string>("gunter"));

interface Props {
  selectionData?: Array<string>;
}

const props = withDefaults(defineProps<Props>(), {});

const searchLoading = ref<boolean>(false);
const pmTableRef = ref<InstanceType<typeof pmTable> | null>(null);
const dateParams = reactive<Record<string, any>>({
  startDate: dayjs().subtract(1, "week").startOf("week").format("YYYY-MM-DD HH:mm:ss"),
  endDate: dayjs().add(2, "week").endOf("week").format("YYYY-MM-DD HH:mm:ss")
});

const loading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
let currentParams: Record<string, any> = {};
const selectionOriginData = ref<Array<any> | null>(null);

const selectionChangeCallBackHandler = inject<SelectionChangeCallBackType>(SelectionChangeCallBackTypeKey);

const selectionChangeHandler = val => {
  selectionOriginData.value = val;
  selectionChangeCallBackHandler("factory", val);
};

const submitHandler = (params: any, cb?: (data: any) => any) => {
  loading.value = true;
  currentParams = { ...currentParams, ...params };
  if (chartType.value === "gunter") {
    currentParams = { ...currentParams, ...dateParams };
    queryFactoryPMGanttList(currentParams, () => {
      loading.value = false;
    }).then(res => {
      tableData.value = res.data;
      setTimeout(() => cb && cb(res), 10);
      nextTick(() => pmTableRef.value?.toggleSelection());
      loading.value = false;
    });
  } else if (chartType.value === "chart") {
    queryFactoryPMList(currentParams, () => {
      loading.value = false;
    }).then(res => {
      tableData.value = res.data;
      setTimeout(() => cb && cb(res.data), 10);
      nextTick(() => pmTableRef.value?.toggleSelection());
      loading.value = false;
    });
  }
};

const resetHandler = () => {
  selectionChangeHandler(null);
  if (currentParams?.sortColumn || currentParams?.sortOrder) {
    delete currentParams.sortColumn;
    delete currentParams.sortOrder;
    pmTableRef.value.clearSort();
  }
};

const sortChangeHandler = (params: any) => {
  if (params) {
    submitHandler(params);
  } else if (currentParams?.sortColumn || currentParams?.sortOrder) {
    delete currentParams.sortColumn;
    delete currentParams.sortOrder;
    submitHandler({});
  }
};

const clearSelection = () => {
  pmTableRef.value.clearSelection();
};

const exportFn = async () => {
  if (selectionOriginData.value?.length) {
    const planNos = selectionOriginData.value.map(item => item.planNo);
    await proxy.download("post", "/fab/api/v1/pm/device/list/export", { ...currentParams, planNos });
    PxMessage.success("导出成功！");
  } else {
    PxMessage.warning("请选择需要导出的厂务设备PM计划！");
  }
};

defineExpose({ tableData, currentParams, submitHandler, clearSelection, exportFn });
</script>

<template>
  <div v-loading="searchLoading" class="factory">
    <div class="factory-pm-title">
      <pmTitle v-model:lock="lock" v-model:loading="searchLoading" :chart="1" @submit="submitHandler" @reset="resetHandler" />
    </div>
    <div class="factory-pm-table">
      <pmTable
        ref="pmTableRef"
        v-model:loading="loading"
        v-model:startDate="dateParams.startDate"
        v-model:endDate="dateParams.endDate"
        :chart="1"
        :data="tableData"
        :selectionData="selectionData"
        @date-change="submitHandler"
        @sort-change="sortChangeHandler"
        @selection-change="val => selectionChangeHandler(val)"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.factory {
  width: 100%;
  height: 100%;

  .factory-pm-title {
    width: 100%;
  }

  .factory-pm-table {
    width: 100%;
    margin-top: 16px;
  }
}
</style>
